<template>
  <div class="login">
    <h2 class="login-head">预算报账管理系统</h2>
    <div class="login-form">
      <van-form @submit="onSubmit" class="van-form">
        <van-cell-group inset>
          <van-field
            v-model="formData.username"
            name="username"
            label="用户名"
            required
            clear-icon
            clear-trigger
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="formData.password"
            type="password"
            name="password"
            required
            clear-icon
            clear-trigger
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />

        </van-cell-group>
        <div class="checked-list">
            <van-checkbox-group v-model="formData.checked" shape="square" class="checked-list-form">
            <van-checkbox name="a" >保存账号</van-checkbox>
            <van-checkbox name="b" @click="loadLastLogin" class="list-form">登录上次使用的账号</van-checkbox>
          </van-checkbox-group>

        </div>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
// import { ref,reactive } from 'vue'
import Cookies from "js-cookie";
import {encrypt, decrypt} from "@/utils/jsencrypt";

import useUserStore from '@/store/modules/user';

import { useRouter } from "vue-router";

import initListStore from '@/store/modules/initList'

const router = useRouter();

const formData = ref({
    username: '',
    password: '',
    checked: ['a', 'b']
  })

  const onSubmit = (values) => {

    // loading.value = true;
    // 调用action的登录方法
    // console.log('values', values);
    // console.log('formData', formData.value);
    // console.log('checked', formData.value.checked);

    // console.log('checked==b', formData.value.checked.includes('b'));
    // if (formData.value.checked=='b') {
    //   loadLastLogin();
    // }
    useUserStore().h5Login(formData.value).then((res) => {

      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      // console.log('checked==a', formData.value.checked.includes('a'));
      if (formData.value.checked.includes('a')) {
        // console.log('checked==a->saveLastLogin', formData.value.checked.includes('a'));

        // console.log('inFormData=', formData);
        saveLastLogin(formData.value);
        Cookies.set("h5_username", formData.value.username, { expires: 30 });
        Cookies.set("h5_password", encrypt(formData.value.password), { expires: 30 });
        // Cookies.set("h5_rememberMe", formData.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("h5_username");
        Cookies.remove("h5_password");
        // Cookies.remove("h5_rememberMe");
      }
      // console.log('login res=======>', res);
     
      setTimeout(() => {
        useUserStore().getH5Info().then(() => {
          router.push({path: '/h5_home'})
          initListStore().publicList()
          initListStore().baseList()
          initListStore().budgetList()
          initListStore().expenditureList()
          initListStore().contractList()
        })
        
      })
      // router.push({ path: redirect.value || "/" });
    }).catch((error) => {
      // loading.value = false;

      console.log('login res==>', res);
      console.error('error submit', error);
      console.log('error submit', values);
      // 重新获取验证码
      // if (captchaType.value === 'image' || captchaType.value === 'static') {
      //   getCode();
      // }
    })
    // useUserStore

  }

async function getCode() {
  if (captchaType.value === 'image') {
    let res = await doGet(svc, '/base/captcha/captchaImage', {type: 'math'}, false)
    if (res) {
      codeUrl.value = "data:image/gif;base64," + res.img
      formData.value.uuid = res.uuid
    }
  }
  if (captchaType.value === 'static') {
    let res = {
      "msg": "操作成功",
      "img": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAA8AKADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/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fJ/wAaX/hJbz/nlB/3yf8AGj20Q9tE6RLSNTkKKsqoUcVyf/CT3v8Azyt/++W/xpf+Eovf+eVv/wB8t/jR7aIe2idaYww5FKkKqeBXJf8ACVX3/PK3/wC+W/xpf+Ervv8Anlbf98t/jR7aIe2idc8CyDBGajXT4Qc7BXLf8Jbf/wDPG2/75b/Gl/4S/UP+eNt/3y3/AMVR7aIe2idgltGvRRVhUA6CuI/4TDUP+eNr/wB8t/8AFUv/AAmWo/8APG1/75b/AOKo9tEPbRO6ApwFcJ/wmeo/88bX/vhv/iqX/hNdS/54Wn/fDf8AxVHtoh7aJ3flg9RT0jC9BXBf8JtqX/PC0/74b/4ql/4TjU/+eFp/3w3/AMVR7aIe2ieggVV1f/kB6h/17Sf+gmuK/wCE51P/AJ4Wn/fDf/FVHc+M9RurWa3eG1CSoyMVVsgEY4+aplWjZilVjZn/2Q==",
      "code": 200,
      "uuid": "c5d7bdfcf0a342859329d9869f2768c0"
    }
    codeUrl.value = "data:image/gif;base64," + res.img
    formData.value.uuid = res.uuid
  }
}

function getCookie() {
  const username = Cookies.get("h5_username");
  const password = Cookies.get("h5_password");
  const rememberMe = Cookies.get("h5_rememberMe");
  formData.value.username = isNullOrUndefined(username) ? formData.value.username : username
  formData.value.password = isNullOrUndefined(password) ? formData.value.password : decrypt(password)
  formData.value.rememberMe = isNullOrUndefined(rememberMe) ? false : Boolean(rememberMe)
}
//保存用户信息到localStorage
const saveLastLogin=(inFormData) => {
  // console.log('saveLastLogin begin');
  // console.log('saveLastLogin ing inFormData',inFormData);
  // console.log('saveLastLogin ing username',inFormData.username);
  // console.log('saveLastLogin ing password',encrypt(inFormData.password));
  const userLoginInfo = {
    username: inFormData.username,
    password: encrypt(inFormData.password),
    checked: inFormData.checked
  }
  // console.log('saveLastLogin ing',JSON.stringify(userLoginInfo));
  localStorage.setItem('h5_lastLogin', JSON.stringify(userLoginInfo));

  // const lastLogin = localStorage.getItem('h5_lastLogin');
  // console.log('saveLastLogin having', lastLogin);
  // console.log('saveLastLogin having JSON.parse', JSON.parse(lastLogin));
};
//从localStorage获取用户登录信息
const loadLastLogin=() => {

  // console.log('formData.value.checked', formData.value.checked);
  // console.log('formData.value.checked', formData.value.checked.includes('b'));
  if (formData.value.checked.includes('b')) {
    const lastLogin = localStorage.getItem('h5_lastLogin');
    // console.log('lastLogin=', lastLogin);
    // console.log('lastLogin JSON=', JSON.parse(lastLogin));
    if(lastLogin){
      const lastLoginInfo = JSON.parse(lastLogin);
      // console.log('lastLogin username=', lastLoginInfo.username);
      // console.log('lastLogin password=', decrypt(lastLoginInfo.password));
      // let userLoginInfo = {
      //   username: lastLoginInfo.username,
      //   password: decrypt(lastLoginInfo.password),
      //   checked: ['a','b']
      // }
      // console.log('userLoginInfo =', userLoginInfo);
      // if (userLoginInfo) {
      formData.value.username=lastLoginInfo.username;
      formData.value.password=decrypt(lastLoginInfo.password);
      formData.value.checked=['a','b'];
    }
    // }
  }
}



</script>
<style scoped lang="scss">
.login {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  margin: 0 auto;
  background: #fff;
  .login-head {
    display: flex;
    justify-content: center;
    margin-top: 12.5rem;
  }
}
.login-form {
  display: flex;
  justify-content: center;
  margin-top: 3.125rem;
}
.van-form {
  width: 90%;
}
.van-cell-group--inset {
  margin: 0;
}
.checked-list-form {
  display: flex;
  align-items: center;
  margin-top: 1.25rem;
}
.list-form {
  margin-left: 1.25rem;
}
</style>


